import React from 'react'
import ReactDom from 'react-dom'
import './index.css'

// 格子
function Square ({onClick,value}){
  return(
    <button className='square' onClick={onClick}>{value}</button>
  )
}

// 棋盘
class Board extends React.PureComponent {
  renderSquare(i){
    return(
      <Square
        value={this.props.squares[i]}
        onClick={()=>this.props.onClick(i)}
      />
    )
  }
  render() {
    return(
      <div>
        {[0,3,6].map(item=>
          <div key={item} className="board-row">
            {this.renderSquare(item)}
            {this.renderSquare(item+1)}
            {this.renderSquare(item+2)}
          </div>
        )}
      </div>
    )
  }
}

// 游戏对象（历史、状态保存）
class Game extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      history:[
        {
          squares: Array(9).fill(null)
        }
      ],
      stepNumber: 0,
      xIsNext: true
    }
  };
  handleClick(i){
    const history = this.state.history.slice(0,this.state.stepNumber+1);
    const current = history[history.length-1];
    const squares = current.squares.slice();
    // 计算是否胜利
    if(calculateWinner(squares) || squares[i]){
      return;
    }

    // 赋值
    squares[i] = this.state.xIsNext?'X':'O';

    // 改变state
    this.setState(
      {
        history:history.concat({
          squares
        }),
        xIsNext: !this.state.xIsNext,
        stepNumber: history.length
      }
    )
  };
  jumpTo(step){
    this.setState({
      stepNumber: step,
      xIsNext: (step%2)===0
    })
  };
  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);
    // 判断状态 显示游戏结果
    let status;
    if(winner){
      status = 'Winner is ' + winner + ' !  Game Over~'
    }else{
      status = 'Next player is ' + (this.state.xIsNext?'X':'O')
    }
    // 游戏步骤 回溯历史
    const moves = history.map((move,step)=>{
      let desc = step? '回溯到第'+step+'步':'游戏开始';
      return (
        <li key={step}>
          <button onClick={()=>this.jumpTo(step)}>{desc}</button>
        </li>
      )
    });

    return(
      <div className="game">
        <div className="game-board">
          <Board
            squares={current.squares}
            onClick={(i)=>this.handleClick(i)}
          />
        </div>
        <div className="game-info">
          <div className='status'>{status}</div>
          <ol>{moves}</ol>
        </div>
      </div>
    )
  }
}

// 满足条件 判断胜者
function calculateWinner(squares){
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for(let i=0;i<lines.length;i+=1){
    const [a,b,c] = lines[i];
    if(squares[a] && squares[a]===squares[b] && squares[a]===squares[c]){
      return squares[a]
    }
  }
  return null;
}

// 挂载组件
ReactDom.render(
  <Game />,
  document.getElementById('root')
);
